<template>
  <div>
    <h1 id="last">销售成本和计划</h1>
    <div class="controls">
      日期：<input v-model="startDate" type="month" @change="applyFilters" />
      筛选日期：<input v-model="endDate" type="month" @change="applyFilters" />
      <button class="repeat" @click="resetFilters">重置</button>
      <button class="add" @click="showPopup">新增</button>
      <button class="out" @click="exportExcel">导出excel文件</button>
    </div>
    <table class="tab" id="cashTable">
      <thead>
        <tr>
          <th>年/月</th>
          <th>增值税</th>
          <th>销售净收入</th>
          <th>总成本</th>
          <th>利润</th>
          <th>企业所得税</th>
          <th>其他</th>
          <th>净收入</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in paginatedData" :key="index">
          <td>{{ item.date }}</td>
          <td>{{ item.vat }}</td>
          <td>{{ item.net_sales_revenue }}</td>
          <td>{{ item.total_cost }}</td>
          <td>{{ item.profit }}</td>
          <td>{{ item.corporate_income }}</td>
          <td>{{ item.other }}</td>
          <td>{{ item.net_income_after }}</td>
          <td>
            <button class="bianji" @click="editItem(index)">编辑</button>
            <button class="shanchu" @click="deleteItem(index)">删除</button>
          </td>
        </tr>
      </tbody>
    </table>
    <div class="pagination">
      <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
      <span>第 {{ currentPage }} 页，共 {{ totalPages }} 页</span>
      <button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
    </div>
    <!-- 新增弹窗 -->
    <div v-if="showAddPopup" class="popup">
      <div class="popup-content">
        <span class="close" @click="showAddPopup = false">&times;</span>
        <label for="editDate">年/月：</label>
        <input v-model="newItem.date" type="month" id="editDate">
        <h2>成本</h2>
        <div class="row-group">
          <div class="input-group">
            <label for="cost">租金：</label>
            <input v-model.number="newItem.cost" type="number" id="cost" placeholder="请输入:">
          </div>
          <div class="input-group">
            <label for="utility">公共事业：</label>
            <input v-model.number="newItem.utility" type="number" id="utility" placeholder="请输入:">
          </div>
          <div class="input-group">
            <label for="marketing">营销：</label>
            <input v-model.number="newItem.marketing" type="number" id="marketing" placeholder="请输入:">
          </div>
          <div class="input-group">
            <label for="insurance">保险：</label>
            <input v-model.number="newItem.insurance" type="number" id="insurance" placeholder="请输入:">
          </div>
          <div class="input-group">
            <label for="registration">注册登记费：</label>
            <input v-model.number="newItem.registration" type="number" id="registration" placeholder="请输入:">
          </div>
          <div class="input-group">
            <label for="repair">维修费：</label>
            <input v-model.number="newItem.repair" type="number" id="repair" placeholder="请输入:">
          </div>
          <div class="input-group">
            <label for="water">水电费：</label>
            <input v-model.number="newItem.water" type="number" id="water" placeholder="请输入:">
          </div>
          <div class="input-group">
            <label for="depreciation">折旧费：</label>
            <input v-model.number="newItem.depreciation" type="number" id="depreciation" placeholder="请输入:">
          </div>
          <div class="input-group">
            <label for="totalCost">总成本：</label>
            <input :value="totalCost" type="number" id="totalCost" readonly>
          </div>
          <div class="input-group">
            <label for="profit">利润：</label>
            <input :value="profit" type="number" id="profit" readonly>
          </div>
          <div class="input-group">
            <label for="corporateTax">企业所得税：</label>
            <input :value="corporateTax" type="number" id="corporateTax" readonly>
          </div>
          <div class="input-group">
            <label for="otherCost">其他：</label>
            <input :value="otherCost" type="number" id="otherCost" readonly>
          </div>
        </div>
        <h2>销售</h2>
        <div class="row-group">
          <div class="input-group">
            <label for="product">含税销售收入：</label>
            <input v-model.number="newItem.product" type="number" id="product" placeholder="请输入:">
          </div>
          <div class="input-group">
            <label for="incomeTax">增值税：</label>
            <input :value="incomeTax" type="number" id="incomeTax" readonly>
          </div>
          <div class="input-group">
            <label for="netIncome">销售净收入：</label>
            <input :value="netIncome" type="number" id="netIncome" readonly>
          </div>
        </div>
        <button @click="addItem">提交保存</button>
      </div>
    </div>
    <!-- 编辑弹窗 -->
    <div v-if="showEditPopup" class="popup">
      <div class="popup-content">
        <span class="close" @click="hidePopups">&times;</span>
        <label for="editDate">年/月：</label>
        <input v-model="currentItem.date" type="month" id="editDate">
        <h2>成本</h2>
        <div class="row-group">
          <div class="input-group">
            <label for="cost">租金：</label>
            <input v-model.number="currentItem.cost" type="number" id="cost" placeholder="请输入:">
          </div>
          <div class="input-group">
            <label for="utility">公共事业：</label>
            <input v-model.number="currentItem.utility" type="number" id="utility" placeholder="请输入:">
          </div>
          <div class="input-group">
            <label for="marketing">营销：</label>
            <input v-model.number="currentItem.marketing" type="number" id="marketing" placeholder="请输入:">
          </div>
          <div class="input-group">
            <label for="insurance">保险：</label>
            <input v-model.number="currentItem.insurance" type="number" id="insurance" placeholder="请输入:">
          </div>
          <div class="input-group">
            <label for="registration">注册登记费：</label>
            <input v-model.number="currentItem.registration" type="number" id="registration" placeholder="请输入:">
          </div>
          <div class="input-group">
            <label for="repair">维修费：</label>
            <input v-model.number="currentItem.repair" type="number" id="repair" placeholder="请输入:">
          </div>
          <div class="input-group">
            <label for="water">水电费：</label>
            <input v-model.number="currentItem.water" type="number" id="water" placeholder="请输入:">
          </div>
          <div class="input-group">
            <label for="depreciation">折旧费：</label>
            <input v-model.number="currentItem.depreciation" type="number" id="depreciation" placeholder="请输入:">
          </div>
          <div class="input-group">
            <label for="totalCost">总成本：</label>
            <input :value="currentTotalCost" type="number" id="totalCost" readonly>
          </div>
          <div class="input-group">
            <label for="profit">利润：</label>
            <input :value="currentProfit" type="number" id="profit" readonly>
          </div>
          <div class="input-group">
            <label for="corporateTax">企业所得税：</label>
            <input :value="currentCorporateTax" type="number" id="corporateTax" readonly>
          </div>
          <div class="input-group">
            <label for="otherCost">其他：</label>
            <input :value="currentOtherCost" type="number" id="otherCost" readonly>
          </div>
        </div>
        <h2>销售</h2>
        <div class="row-group">
          <div class="input-group">
            <label for="product">含税销售收入：</label>
            <input v-model.number="currentItem.product" type="number" id="product" placeholder="请输入:">
          </div>
          <div class="input-group">
            <label for="incomeTax">增值税：</label>
            <input :value="currentIncomeTax" type="number" id="incomeTax" readonly>
          </div>
          <div class="input-group">
            <label for="netIncome">销售净收入：</label>
            <input :value="currentNetIncome" type="number" id="netIncome" readonly>
          </div>
        </div>
        <button @click="updateItem">提交保存</button>
      </div>
    </div>
  </div>
</template>
<script>
import axios from 'axios';
import * as XLSX from 'xlsx';

export default {
  data() {
    return {
      items: [],
      newItem: {
        date: '',
        product: 0,
        cost: 0,
        utility: 0,
        marketing: 0,
        insurance: 0,
        registration: 0,
        repair: 0,
        water: 0,
        depreciation: 0,
      },
      currentItem: {},
      currentItemIndex: -1,
      showAddPopup: false,
      showEditPopup: false,
      startDate: '',
      pageSize: 8,
      currentPage: 1,
      userId: null, // Store userId here
    };
  },
  created() {
    this.userId = localStorage.getItem('userId');
    if (!this.userId) {
      alert('请先登录');
      this.$router.push('/login');
    } else {
      this.applyFilters();
    }
  },
  computed: {
    totalPages() {
      return Math.ceil(this.items.length / this.pageSize);
    },
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.items.slice(start, end);
    },
    totalCost() {
      const { cost, utility, marketing, insurance, registration, repair, water, depreciation } = this.newItem;
      return cost + utility + marketing + insurance + registration + repair + water + depreciation;
    },
    profit() {
      return this.newItem.product - this.totalCost;
    },
    incomeTax() {
      return this.newItem.product * 0.13; // 假设增值税为13%
    },
    corporateTax() {
      return this.profit * 0.25; // 假设企业所得税为25%
    },
    otherCost() {
      return this.totalCost * 0.1; // 假设其他费用为总成本的10%
    },
    netIncome() {
      return this.newItem.product - this.totalCost - this.corporateTax - this.otherCost;
    },
    currentTotalCost() {
      const { cost, utility, marketing, insurance, registration, repair, water, depreciation } = this.currentItem;
      return cost + utility + marketing + insurance + registration + repair + water + depreciation;
    },
    currentProfit() {
      return this.currentItem.product - this.currentTotalCost;
    },
    currentIncomeTax() {
      return this.currentItem.product * 0.13;
    },
    currentCorporateTax() {
      return this.currentProfit * 0.25;
    },
    currentOtherCost() {
      return this.currentTotalCost * 0.1;
    },
    currentNetIncome() {
      return this.currentItem.product - this.currentTotalCost - this.currentCorporateTax - this.currentOtherCost;
    },
  },
  methods: {
  editItem(index) {
    console.log('Edit button clicked for item:', index);
    this.currentItem = { ...this.items[index] }; // 深拷贝当前编辑项
    this.currentItemIndex = index;
    this.showEditPopup = true; // 显示编辑弹窗
  },
  showPopup() {
    this.showAddPopup = true;
  },
  hidePopups() {
    this.showAddPopup = false;
    this.showEditPopup = false;
  },
  applyFilters() {
  const start = this.startDate ? new Date(this.startDate) : new Date('1900-01-01');
  const end = this.endDate ? new Date(this.endDate) : new Date('2100-12-31');
  
  // 检查日期有效性
  if (start > end) {
    alert('结束日期不能早于开始日期');
    return;
  }

  axios.get('http://82.156.19.25:5000/get_plancome_data', {
    params: {
      user_id: this.userId,
      start_date: this.startDate,
      end_date: this.endDate
    }
  })
  .then(response => {
    // 过滤数据以确保它在日期范围内
    this.items = response.data.plancome.filter(item => {
      const itemDate = new Date(item.date);
      return itemDate >= start && itemDate <= end;
    });
    this.items.sort((a, b) => b.id - a.id); // 按 id 逆序排列
    this.currentPage = 1;
  })
  .catch(error => {
    console.error('Error fetching data:', error);
  });
},
  resetFilters() {
    this.startDate = '';
    this.applyFilters();
  },
  addItem() {
  const newItem = {
    ...this.newItem,
    user_id: this.userId,
    date: `${this.newItem.date}-01`,
    vat: this.incomeTax,
    net_sales_revenue: this.netIncome,
    total_cost: this.totalCost,
    profit: this.profit,
    corporate_income: this.corporateTax,
    other: this.otherCost,
    net_income_after: this.netIncome,
  };

  axios.post('http://82.156.19.25:5000/add_plancome_data', newItem)
    .then(() => {
      this.applyFilters(); // 重新加载数据
      this.hidePopups();
    })
    .catch(error => {
      console.error('Error adding item:', error);
    });
},
updateItem() {
  const updatedItem = {
    ...this.currentItem,
    user_id: this.userId,
    id: this.currentItem.id,
    date: `${this.currentItem.date}-01`,
    vat: this.currentIncomeTax,
    net_sales_revenue: this.currentNetIncome,
    total_cost: this.currentTotalCost,
    profit: this.currentProfit,
    corporate_income: this.currentCorporateTax,
    other: this.currentOtherCost,
    net_income_after: this.currentNetIncome,
  };

  axios.put('http://82.156.19.25:5000/update_plancome_data', updatedItem)
    .then(response => {
      if (response.data.success) {
        // 找到并更新 items 数组中的对应项
        const index = this.items.findIndex(item => item.id === updatedItem.id);
        if (index !== -1) {
          // 直接更新对象
          this.items[index] = updatedItem;
        }
        this.items.sort((a, b) => b.id - a.id); // 确保逆序排列
        this.hidePopups();
        this.currentPage = 1; // 确保在第一页显示
      } else {
        console.error('Update failed:', response.data.message);
        alert('请输入完整');
      }
    })
    .catch(error => {
      console.error('Error updating item:', error.response ? error.response.data : error.message);
    });
},
  deleteItem(index) {
    const confirmed = confirm('确定删除此项吗？');
    if (confirmed) {
      axios.delete('http://82.156.19.25:5000/delete_plancome_data', { data: { user_id: this.userId, id: this.items[index].id } })
        .then(() => {
          this.items.splice(index, 1); // 从 items 数组中删除
        })
        .catch(error => {
          console.error('Error deleting item:', error);
        });
    }
  },
  exportExcel() {
  // 检查数据有效性
  if (!Array.isArray(this.items)) {
    console.error('Items should be an array');
    return;
  }

  // 创建导出的表格数据
  const tableData = this.items.map(item => [
    item.date,
    (Number(item.vat) || 0).toFixed(2),
    (Number(item.net_sales_revenue) || 0).toFixed(2),
    (Number(item.total_cost) || 0).toFixed(2),
    (Number(item.profit) || 0).toFixed(2),
    (Number(item.corporate_income) || 0).toFixed(2),
    (Number( item.other) || 0).toFixed(2),
    (Number(item.net_income_after) || 0).toFixed(2)
  ]);

  // 添加表头
  tableData.unshift([
    '年/月',
    '增值税',
    '销售净收入',
    '总成本',
    '利润',
    '企业所得税',
    '其他',
    '净收入'
  ]);

  // 计算总计
  const totalRevenue = this.items.reduce((sum, item) => sum + (Number(item.net_sales_revenue) || 0), 0);
  const totalCost = this.items.reduce((sum, item) => sum + (Number(item.total_cost) || 0), 0);
  const totalProfit = this.items.reduce((sum, item) => sum + (Number(item.profit) || 0), 0);
  const totalCorporateTax = this.items.reduce((sum, item) => sum + (Number(item.corporate_income) || 0), 0);
  const totalOtherCost = this.items.reduce((sum, item) => sum + (Number(item.other) || 0), 0);
  const totalNetProfit = this.items.reduce((sum, item) => sum + (Number(item.net_income_after ) || 0), 0);

  // 添加总计行
  tableData.push([
    '总计',
    '', // 第二列留空
    totalRevenue.toFixed(2), // 销售净收入总计
    totalCost.toFixed(2), // 总成本总计
    totalProfit.toFixed(2), // 利润总计
    totalCorporateTax.toFixed(2), // 企业所得税总计
    totalOtherCost.toFixed(2), // 其他总计
    totalNetProfit.toFixed(2) // 净收入总计
  ]);

  // 创建 Excel 工作表
  const worksheet = XLSX.utils.aoa_to_sheet(tableData);

  // 设置单元格样式
  const range = XLSX.utils.decode_range(worksheet['!ref']);
  for (let R = range.s.r; R <= range.e.r; ++R) {
    for (let C = range.s.c; C <= range.e.c; ++C) {
      const cell_address = { c: C, r: R };
      const cell_ref = XLSX.utils.encode_cell(cell_address);
      if (!worksheet[cell_ref]) worksheet[cell_ref] = {}; // 如果单元格为空则初始化
      if (!worksheet[cell_ref].s) worksheet[cell_ref].s = {}; // 初始化样式对象

      // 设置单元格样式
      if (R === 0) {
        // 表头行
        worksheet[cell_ref].s.font = { bold: true };
        worksheet[cell_ref].s.fill = { fgColor: { rgb: "FFFF00" } }; // 黄色背景色
      } else if (R === tableData.length - 1) {
        // 总计行
        worksheet[cell_ref].s.font = { bold: true };
      }
      worksheet[cell_ref].s.alignment = { horizontal: 'center', vertical: 'center' }; // 设置水平和垂直居中
    }
  }

  // 自动调整列宽
  const colWidths = tableData[0].map((_, i) => ({
    wch: Math.max(...tableData.map(row => (row[i] ? row[i].toString().length : 10))) + 4 // 增加一点空间
  }));
  worksheet['!cols'] = colWidths;

  // 创建工作簿
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, '销售成本和计划');

  // 导出 Excel 文件
  XLSX.writeFile(workbook, '销售成本和计划.xlsx');
},
  prevPage() {
    if (this.currentPage > 1) {
      this.currentPage--;
    }
  },
  nextPage() {
    if (this.currentPage < this.totalPages) {
      this.currentPage++;
    }
  },
},
mounted() {
  if (this.userId) {
    this.applyFilters();
  }
},

};
</script>

<style scoped>
.row-group {
  display: flex;
  flex-wrap: wrap;
  gap: 15px; /* 调整行间距 */
}

.input-group {
  flex: 1 1 calc(50% - 15px); /* 每行两个输入框，减去间距 */
  box-sizing: border-box;
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.container {
  background-color: #f5f5f5; 
  padding: 20px;
  border-radius: 8px;
}
body {
  font-family: Arial, sans-serif;
  background-color: #062745;
  align-items: center;
  flex-direction: column;
  min-height: 100vh;
  margin: 0;
}

.controls {
  margin-left: 120px;
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.controls input[type='text']{
  margin-left: 125px;
  margin-right: 10px;
  padding: 5px;
  border-radius: 4px;
  border: 1px solid #ddd;
}
.controls input[type='month'],
.controls input[type='date'] {
  margin-left: 1px;
  margin-right: 10px;
  padding: 5px;
  border-radius: 4px;
  border: 1px solid #ddd;
}

table {
  border-collapse: collapse;
  width: 100%;
}

table {
  border-collapse: collapse;
  width: 80%;
  margin: 20px 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  background-color: #fff;
}

th,
td {
  border: 1px solid #ddd;
  padding: 12px 15px;
  text-align: center;
}

th {
  background-color: #4caf50;
  color: white;
}

tr:nth-child(even) {
  background-color: #f2f2f2;
}

tr:hover {
  background-color: #f1f1f1;
}

h1 {
  margin-left: 15px;
}
.repeat{
  background-color: rgb(134, 173, 16);
  margin-bottom: 5px;
  margin-top: 10px;
  margin-left: 10px;
  border-radius: 8px;
  border-style: none;
  padding: 5px 20px;
  font-size: 15px;
  color: white;
  transition: background-color 0.3s; /* 添加过渡效果 */
}
.add {
  background-color: rgb(27, 128, 7);
  margin-bottom: 5px;
  margin-top: 10px;
  margin-left: 10px;
  border-radius: 8px;
  border-style: none;
  padding: 5px 20px;
  font-size: 15px;
  color: white;
  transition: background-color 0.3s; /* 添加过渡效果 */
}
.out:hover,
.add:hover,
.bianji:hover,
.shanchu:hover {
  background-color: rgb(103, 17, 240);
}

.out {
  background-color: #f07c3e;
  margin-bottom: 5px;
  margin-top: 10px;
  margin-left: 10px;
  border-radius: 8px;
  border-style: none;
  padding: 5px 20px;
  font-size: 15px;
  color: white;
  transition: background-color 0.3s;
}

.popup {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.popup-content {
  background-color: white;
  padding: 50px;
  border-radius: 8px;
  width: 500px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
  position: relative;
  
}

.close {
  position: absolute;
  right: 20px;
  top: 20px;
  cursor: pointer;
  font-size: 18px;
  color: #333;
}

.bianji {
  background-color: rgb(201, 43, 31);
  margin-bottom: 10px;
  margin-top: 10px;
  margin-left: 10px;
  border-radius: 8px;
  border-style: none;
  padding: 5px 20px;
  font-size: 15px;
  color: white;
  transition: background-color 0.3s; /* 添加过渡效果 */
}
.tab {
  margin-left: 125px;
}
.shanchu {
  background-color: rgb(9, 4, 48);
  margin-bottom: 10px;
  margin-top: 10px;
  margin-left: 10px;
  border-radius: 8px;
  border-style: none;
  padding: 5px 20px;
  font-size: 15px;
  color: white;
  transition: background-color 0.3s; /* 添加过渡效果 */
}

button {
  cursor: pointer;
}
.popup-content input[type='month'],
.popup-content input[type='text'],
.popup-content input[type='number'],
.popup-content input[type='date'] {
  width: 100%;
  padding: 3px;
  margin-bottom: 1px;
  border-radius: 4px;
  border: 1px solid #ddd;
  font-size: 14px;
}

input[type='text']:focus,
input[type='number']:focus,
input[type='month']:focus,
input[type='date']:focus {
  border-color: #4caf50;
}


button {
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 12px 24px;
  cursor: pointer;
  margin-top: 10px;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #45a049;
}


.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
}

.pagination button {
  margin: 0 5px;
  padding: 8px 16px;
  border-radius: 4px;
  background-color: #f2f2f2;
  color: #333;
  border: none;
  cursor: pointer;
  transition: background-color 0.3s;
}

.pagination button:hover {
  background-color: #ddd;
}
.popup-content select {
  width: 106%;
  padding: 9px;
  margin-bottom: 15px;
  border-radius: 4px;
  border: 1px solid #ddd;
  font-size: 14px;
}

select:focus {
  border-color: #4caf50;
}
/* 月份 */
.controls select {
  margin-left: 10px;
  margin-right: 10px;
  padding: 5px;
  border-radius: 4px;
  border: 1px solid #ddd;
}
.hidden-table {
    display: none;
  }
  /* 隐藏数据 */
  .input-group {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.input-group label {
  min-width: 150px;   /* 调节宽度 */
  margin-right: -28px;
}

.input-group input {
  flex: 1;
}

</style>